import*as e from"../../core/common/common.js";import*as t from"../../core/host/host.js";import*as o from"../../core/i18n/i18n.js";import*as r from"../../core/platform/platform.js";import*as i from"../../core/sdk/sdk.js";import*as s from"../../ui/components/icon_button/icon_button.js";import*as n from"../../ui/legacy/legacy.js";import*as a from"../../ui/legacy/theme_support/theme_support.js";const l=new CSSStyleSheet;l.replaceSync(".perfmon-pane{overflow:hidden;--override-color-perf-monitor-cpu:rgb(227 33 33);--override-color-perf-monitor-cpu-task-duration:rgb(154 154 154);--override-color-perf-monitor-cpu-script-duration:rgb(255 165 0);--override-color-perf-monitor-cpu-layout-duration:rgb(138 43 226);--override-color-perf-monitor-cpu-recalc-style-duration:rgb(238 130 238);--override-color-perf-monitor-jsheap:rgb(0 0 255);--override-color-perf-monitor-jsheap-total-size:rgb(153 153 255);--override-color-perf-monitor-jsheap-used-size:rgb(0 0 255);--override-color-perf-monitor-dom-nodes:rgb(11 154 11);--override-color-perf-monitor-js-event-listeners:rgb(154 205 50);--override-color-perf-monitor-documents:rgb(0 0 139);--override-color-perf-monitor-document-frames:rgb(0 139 139);--override-color-perf-monitor-layout-count:rgb(255 105 180);--override-color-perf-monitor-recalc-style-count:rgb(255 20 147)}:host-context(.-theme-with-dark-background) .perfmon-pane{--override-color-perf-monitor-cpu:rgb(242 113 113);--override-color-perf-monitor-cpu-task-duration:rgb(201 201 201);--override-color-perf-monitor-cpu-script-duration:rgb(255 165 0);--override-color-perf-monitor-cpu-layout-duration:rgb(124 29 212);--override-color-perf-monitor-cpu-recalc-style-duration:rgb(179 49 179);--override-color-perf-monitor-jsheap:rgb(153 153 255);--override-color-perf-monitor-jsheap-total-size:rgb(153 153 255);--override-color-perf-monitor-jsheap-used-size:rgb(0 0 255);--override-color-perf-monitor-dom-nodes:rgb(127 255 127);--override-color-perf-monitor-js-event-listeners:rgb(154 205 50);--override-color-perf-monitor-documents:rgb(116 116 255);--override-color-perf-monitor-document-frames:rgb(116 255 255);--override-color-perf-monitor-layout-count:rgb(255 105 180);--override-color-perf-monitor-recalc-style-count:rgb(235 0 127)}.perfmon-pane.suspended{opacity:40%;pointer-events:none}.perfmon-pane .perfmon-chart-suspend-overlay{display:none;font-size:26px;align-items:center;justify-content:center}.perfmon-pane.suspended .perfmon-chart-suspend-overlay{display:flex}.perfmon-control-pane{display:flex;flex-direction:column;padding:6px 0;overflow-x:hidden;overflow-y:auto}.perfmon-chart-container{display:flex;flex:1 1;border-left:1px solid var(--color-details-hairline);overflow-y:auto}.perfmon-chart-container canvas{width:100%}.perfmon-indicator{padding:6px 12px;margin:-1px 0;display:flex;flex-shrink:0;width:210px}.perfmon-indicator:hover,\n.perfmon-indicator:focus-visible{background-color:var(--color-background-elevation-1)}.perfmon-indicator-swatch{margin-right:4px}.perfmon-indicator-title{flex:0 0 115px}.perfmon-indicator:not(.active) .perfmon-indicator-title{color:var(--color-text-secondary)}.perfmon-indicator-value{flex:0 0 55px;text-align:right;overflow:visible}.perfmon-indicator:not(.active) .perfmon-indicator-value{opacity:0%}\n/*# sourceURL=performanceMonitor.css */\n");const c={graphsDisplayingARealtimeViewOf:"Graphs displaying a real-time view of performance metrics",paused:"Paused",cpuUsage:"CPU usage",jsHeapSize:"JS heap size",domNodes:"DOM Nodes",jsEventListeners:"JS event listeners",documents:"Documents",documentFrames:"Document Frames",layoutsSec:"Layouts / sec",styleRecalcsSec:"Style recalcs / sec"},h=o.i18n.registerUIStrings("panels/performance_monitor/PerformanceMonitor.ts",c),m=o.i18n.getLocalizedString.bind(void 0,h);let d,p,u;class f extends n.Widget.HBox{metricsBuffer;pixelsPerMs;pollIntervalMs;scaleHeight;graphHeight;gridColor;controlPane;canvas;animationId;width;height;model;startTimestamp;pollTimer;constructor(e){super(!0),this.contentElement.classList.add("perfmon-pane"),this.metricsBuffer=[],this.pixelsPerMs=.01,this.pollIntervalMs=e,this.scaleHeight=16,this.graphHeight=90,this.gridColor=a.ThemeSupport.instance().getComputedValue("--divider-line"),this.controlPane=new g(this.contentElement);const t=this.contentElement.createChild("div","perfmon-chart-container");this.canvas=t.createChild("canvas"),this.canvas.tabIndex=-1,n.ARIAUtils.setLabel(this.canvas,m(c.graphsDisplayingARealtimeViewOf)),this.contentElement.createChild("div","perfmon-chart-suspend-overlay fill").createChild("div").textContent=m(c.paused),this.controlPane.addEventListener("MetricChanged",this.recalcChartHeight,this),i.TargetManager.TargetManager.instance().observeModels(i.PerformanceMetricsModel.PerformanceMetricsModel,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return d&&!t||(d=new f(500)),d}wasShown(){if(!this.model)return;this.registerCSSFiles([l]),this.controlPane.instantiateMetricData();a.ThemeSupport.instance().addEventListener(a.ThemeChangeEvent.eventName,(()=>{this.controlPane.instantiateMetricData(),this.draw()})),i.TargetManager.TargetManager.instance().addEventListener(i.TargetManager.Events.SuspendStateChanged,this.suspendStateChanged,this),this.model.enable(),this.suspendStateChanged()}willHide(){this.model&&(i.TargetManager.TargetManager.instance().removeEventListener(i.TargetManager.Events.SuspendStateChanged,this.suspendStateChanged,this),this.stopPolling(),this.model.disable())}modelAdded(e){e.target()===i.TargetManager.TargetManager.instance().primaryPageTarget()&&(this.model=e,this.isShowing()&&this.wasShown())}modelRemoved(e){this.model===e&&(this.isShowing()&&this.willHide(),this.model=null)}suspendStateChanged(){const e=i.TargetManager.TargetManager.instance().allTargetsSuspended();e?this.stopPolling():this.startPolling(),this.contentElement.classList.toggle("suspended",e)}startPolling(){this.startTimestamp=0,this.pollTimer=window.setInterval((()=>this.poll()),this.pollIntervalMs),this.onResize();const e=()=>{this.draw(),this.animationId=this.contentElement.window().requestAnimationFrame((()=>{e()}))};e()}stopPolling(){window.clearInterval(this.pollTimer),this.contentElement.window().cancelAnimationFrame(this.animationId),this.metricsBuffer=[]}async poll(){if(!this.model)return;const e=await this.model.requestMetrics(),t=e.timestamp,o=e.metrics;this.metricsBuffer.push({timestamp:t,metrics:o});const r=this.width/this.pixelsPerMs,i=Math.ceil(r/this.pollIntervalMs*2);this.metricsBuffer.length>2*i&&this.metricsBuffer.splice(0,this.metricsBuffer.length-i),this.controlPane.updateMetrics(o)}draw(){const e=this.canvas.getContext("2d");e.save(),e.scale(window.devicePixelRatio,window.devicePixelRatio),e.clearRect(0,0,this.width,this.height),e.save(),e.translate(0,this.scaleHeight);for(const t of this.controlPane.charts())this.controlPane.isActive(t.metrics[0].name)&&(this.drawChart(e,t,this.graphHeight),e.translate(0,this.graphHeight));e.restore(),this.drawHorizontalGrid(e),e.restore()}drawHorizontalGrid(e){const o=a.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-2");e.font="10px "+t.Platform.fontFamily(),e.fillStyle=a.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-50");const r=Date.now()/1e3;for(let t=Math.ceil(r);;--t){const i=this.width-(1e3*(r-t)-this.pollIntervalMs)*this.pixelsPerMs;if(i<-50)break;e.beginPath(),e.moveTo(i,0),e.lineTo(i,this.height),t>=0&&t%10==0&&e.fillText(new Date(1e3*t).toLocaleTimeString(),i+4,12),e.strokeStyle=t%10?o:this.gridColor,e.stroke()}}drawChart(o,r,i){o.save(),o.rect(0,0,this.width,i),o.clip();const s=1.05*this.calcMax(r),n=r.stacked?new Map:null,l=[];for(let e=r.metrics.length-1;e>=0;--e){const t=r.metrics[e];l.push({path:this.buildMetricPath(r,t,i-8,s,e?n:null),color:t.color})}const c=e.Color.parse(a.ThemeSupport.instance().getComputedValue("--color-background"))?.asLegacyColor();if(c)for(const t of l.reverse()){const r=t.color;o.save();const i=e.Color.parse(r);i&&(o.fillStyle=c.blendWith(i.setAlpha(.2).asLegacyColor()).asString()||"",o.fill(t.path),o.strokeStyle=r,o.lineWidth=.5,o.stroke(t.path),o.restore())}o.fillStyle=a.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-50"),o.font=`10px  ${t.Platform.fontFamily()}`,o.fillText(r.title,8,10),this.drawVerticalGrid(o,i-8,s,r),o.restore()}calcMax(e){if(e.max)return e.max;const t=this.width,o=performance.now()-this.pollIntervalMs-t/this.pixelsPerMs;let r=-1/0;for(const t of e.metrics)for(let e=this.metricsBuffer.length-1;e>=0;--e){const i=this.metricsBuffer[e],s=i.metrics.get(t.name);if(void 0!==s&&(r=Math.max(r,s)),i.timestamp<o)break}if(!this.metricsBuffer.length)return 10;const i=Math.pow(10,Math.floor(Math.log10(r)));r=Math.ceil(r/i/2)*i*2;return e.currentMax=.2*r+.8*(e.currentMax||r),e.currentMax}drawVerticalGrid(e,t,o,r){let i=Math.pow(10,Math.floor(Math.log10(o)));const s=Math.floor(o/i);1!==s&&s%2==1&&(i*=2);let n=Math.floor(o/i)*i;const l=o,c=t-18;e.fillStyle=a.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-50"),e.strokeStyle=this.gridColor,e.beginPath();for(let t=0;t<2;++t){const t=h(n),o=v.formatNumber(n,r);e.moveTo(0,t),e.lineTo(4,t),e.moveTo(e.measureText(o).width+12,t),e.lineTo(this.width,t),e.fillText(o,8,h(n)+3),n/=2}function h(e){return Math.round(t-c*e/l)+.5}e.stroke(),e.beginPath(),e.moveTo(0,t+.5),e.lineTo(this.width,t+.5),e.strokeStyle=a.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-2"),e.stroke()}buildMetricPath(e,t,o,i,s){const n=new Path2D,a=o-18;if(a<1)return n;const l=i,c=t.name,h=this.pixelsPerMs,m=performance.now()-this.pollIntervalMs-this.width/h,d=e.smooth;let p=0,u=0,f=0;this.metricsBuffer.length&&(p=(this.metricsBuffer[0].timestamp-m)*h,n.moveTo(p,g(0)),n.lineTo(this.width+5,g(0)),u=g(this.metricsBuffer[this.metricsBuffer.length-1].metrics.get(c)||0),f=this.width+5,n.lineTo(f,u));for(let e=this.metricsBuffer.length-1;e>=0;--e){const t=this.metricsBuffer[e],o=t.timestamp;let i=t.metrics.get(c)||0;s&&(i+=s.get(o)||0,i=r.NumberUtilities.clamp(i,0,1),s.set(o,i));const a=g(i);if(p=(o-m)*h,d){const e=(f+p)/2;n.bezierCurveTo(e,u,e,a,p,a)}else n.lineTo(p,u),n.lineTo(p,a);if(f=p,u=a,o<m)break}return n;function g(e){return Math.round(o-a*e/l)+.5}}onResize(){super.onResize(),this.width=this.canvas.offsetWidth,this.canvas.width=Math.round(this.width*window.devicePixelRatio),this.recalcChartHeight()}recalcChartHeight(){let e=this.scaleHeight;for(const t of this.controlPane.charts())this.controlPane.isActive(t.metrics[0].name)&&(e+=this.graphHeight);this.height=Math.ceil(e*window.devicePixelRatio),this.canvas.height=this.height,this.canvas.style.height=this.height/window.devicePixelRatio+"px"}}class g extends e.ObjectWrapper.ObjectWrapper{element;enabledChartsSetting;enabledCharts;chartsInfo=[];indicators=new Map;constructor(t){super(),this.element=t.createChild("div","perfmon-control-pane"),this.enabledChartsSetting=e.Settings.Settings.instance().createSetting("perfmonActiveIndicators2",["TaskDuration","JSHeapTotalSize","Nodes"]),this.enabledCharts=new Set(this.enabledChartsSetting.get())}instantiateMetricData(){const e={color:void 0,format:void 0,currentMax:void 0,max:void 0,smooth:void 0,stacked:void 0},t=a.ThemeSupport.instance();this.chartsInfo=[{...e,title:m(c.cpuUsage),metrics:[{name:"TaskDuration",color:t.getComputedValue("--override-color-perf-monitor-cpu-task-duration",this.element)},{name:"ScriptDuration",color:t.getComputedValue("--override-color-perf-monitor-cpu-script-duration",this.element)},{name:"LayoutDuration",color:t.getComputedValue("--override-color-perf-monitor-cpu-layout-duration",this.element)},{name:"RecalcStyleDuration",color:t.getComputedValue("--override-color-perf-monitor-cpu-recalc-style-duration",this.element)}],format:"Percent",smooth:!0,stacked:!0,color:t.getComputedValue("--override-color-perf-monitor-cpu",this.element),max:1,currentMax:void 0},{...e,title:m(c.jsHeapSize),metrics:[{name:"JSHeapTotalSize",color:t.getComputedValue("--override-color-perf-monitor-jsheap-total-size",this.element)},{name:"JSHeapUsedSize",color:t.getComputedValue("--override-color-perf-monitor-jsheap-used-size",this.element)}],format:"Bytes",color:t.getComputedValue("--override-color-perf-monitor-jsheap")},{...e,title:m(c.domNodes),metrics:[{name:"Nodes",color:t.getComputedValue("--override-color-perf-monitor-dom-nodes",this.element)}]},{...e,title:m(c.jsEventListeners),metrics:[{name:"JSEventListeners",color:t.getComputedValue("--override-color-perf-monitor-js-event-listeners",this.element)}]},{...e,title:m(c.documents),metrics:[{name:"Documents",color:t.getComputedValue("--override-color-perf-monitor-documents",this.element)}]},{...e,title:m(c.documentFrames),metrics:[{name:"Frames",color:t.getComputedValue("--override-color-perf-monitor-document-frames",this.element)}]},{...e,title:m(c.layoutsSec),metrics:[{name:"LayoutCount",color:t.getComputedValue("--override-color-perf-monitor-layout-count",this.element)}]},{...e,title:m(c.styleRecalcsSec),metrics:[{name:"RecalcStyleCount",color:t.getComputedValue("--override-color-perf-monitor-recalc-style-count",this.element)}]}],this.element.removeChildren(),this.indicators=new Map;for(const e of this.chartsInfo){const t=e.metrics[0].name,o=this.enabledCharts.has(t),r=new v(this.element,e,o,this.onToggle.bind(this,t));this.indicators.set(t,r)}}onToggle(e,t){t?this.enabledCharts.add(e):this.enabledCharts.delete(e),this.enabledChartsSetting.set(Array.from(this.enabledCharts)),this.dispatchEventToListeners("MetricChanged")}charts(){return this.chartsInfo}isActive(e){return this.enabledCharts.has(e)}updateMetrics(e){for(const t of this.indicators.keys()){const o=e.get(t);if(void 0!==o){const e=this.indicators.get(t);e&&e.setValue(o)}}}}class v{info;active;onToggle;element;swatchElement;valueElement;color;constructor(e,t,o,r){this.color=t.color||t.metrics[0].color,this.info=t,this.active=o,this.onToggle=r,this.element=e.createChild("div","perfmon-indicator"),this.swatchElement=new s.Icon.Icon,this.swatchElement.classList.add("perfmon-indicator-swatch"),this.updateSwatchElement(),this.element.appendChild(this.swatchElement),this.element.createChild("div","perfmon-indicator-title").textContent=t.title,this.valueElement=this.element.createChild("div","perfmon-indicator-value"),this.valueElement.style.color=this.color,this.element.addEventListener("click",(()=>this.toggleIndicator())),this.element.addEventListener("keypress",(e=>this.handleKeypress(e))),this.element.classList.toggle("active",o),n.ARIAUtils.markAsCheckbox(this.element),n.ARIAUtils.setChecked(this.element,this.active),this.element.tabIndex=0}static formatNumber(e,t){switch(p||(p=new Intl.NumberFormat("en-US",{maximumFractionDigits:1}),u=new Intl.NumberFormat("en-US",{maximumFractionDigits:1,style:"percent"})),t.format){case"Percent":return u.format(e);case"Bytes":return r.NumberUtilities.bytesToString(e);default:return p.format(e)}}setValue(e){this.valueElement.textContent=v.formatNumber(e,this.info)}updateSwatchElement(){const e=this.active?this.color:"var(--icon-disabled)";this.swatchElement.data={iconName:"checkmark",color:e,width:"16px",height:"14px"}}toggleIndicator(){this.active=!this.active,this.updateSwatchElement(),this.element.classList.toggle("active",this.active),n.ARIAUtils.setChecked(this.element,this.active),this.onToggle(this.active)}handleKeypress(e){const t=e;" "!==t.key&&"Enter"!==t.key||this.toggleIndicator()}}const w=new Intl.NumberFormat("en-US",{maximumFractionDigits:1});var b=Object.freeze({__proto__:null,PerformanceMonitorImpl:f,ControlPane:g,MetricIndicator:v,format:w});export{b as PerformanceMonitor};
